package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author lupengning
 * @since 2021-05-27
 */
@Api(tags = "数据字典管理")
//@CrossOrigin
@RestController
@RequestMapping("/admin/core/dict")
public class AdminDictController {

  @Resource
  private DictService dictService;

  /**
   * @param file
   * @return
   */
  @ApiOperation("Excel数据的批量导入")
  @PostMapping("/import")
  public R batchImport(@RequestParam("file") MultipartFile file) {
    try {
      dictService.importData(file.getInputStream());
      return R.ok().message("数据批量导入成功！");
    } catch (IOException e) {
      throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
    }
  }

  /**
   * 文件下载（失败了会返回一个有部分数据的Excel）
   * <p>
   * 1. 创建excel对应的实体对象 参照{link DownloadData}
   * <p>
   * 2. 设置返回的 参数
   * <p>
   * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
   */
  @ApiOperation("数据字典导出到excel")
  @GetMapping("/export")
  public void export(HttpServletResponse response) throws IOException {
    // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf-8");
    // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
    String fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet()
        .doWrite(dictService.listDictData());
  }

  @ApiOperation("根据parentId获取数据字典")
  @GetMapping("/listByParentId/{parentId}")
  public R listByParentId(@ApiParam(value = "上级节点Id", required = true)
                          @PathVariable Long parentId) {
    List<Dict> dictList = dictService.listByParentId(parentId);
    return R.ok().data("list",dictList);
  }
}

